package com.sentiment.shiro;

import java.util.Date;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.LogoutFilter;

import com.sentiment.bean.LogOperation;
import com.sentiment.database.bean.UserLog;
import com.sentiment.database.dbUtil.DbUtil;
import com.sentiment.tools.Format;

public class MyLogout extends LogoutFilter{

	@Override
	protected boolean preHandle(ServletRequest request, ServletResponse response)
			throws Exception {
		Subject subject = SecurityUtils.getSubject();
		Session session = subject.getSession();
    	ActiveUser activeUser = (ActiveUser) subject.getPrincipal();
    	if(activeUser != null){
	    	UserLog log = new UserLog(activeUser.getUser_id(), Format.date2String(new Date(), 3), LogOperation.loginout, session.getHost());
	    	DbUtil db = new DbUtil();
			db.openConnection(UserLog.dbName, UserLog.collection);
	    	db.insert(log.toDocument());
	    	db.closeConnection();
    	}
		return super.preHandle(request, response);
	}
}
